/**
 * Created by LaiGuiming on 2017/6/29 0029.
 */
$(function () {
    //时间控件
    $('.input-group.date').datepicker({
        keyboardNavigation: false,
        forceParse: false,
        calendarWeeks: true,
        autoclose: true
    });

    //初始化复选框
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
    //百度编辑器初始化
    if($("#editor").size()>0) {
        UE.getEditor('editor', {
            initialFrameWidth: "100%", //初始化选项
        })
    }

    if($("#fileInput").size()>0) {
        //图片上传设置
        initFileInput("fileInput");
    }

    //点击提交
    $("#btn_sub").click(function () {
        submitForm();
    });
});

/**
 * 表单提交
 */
function submitForm() {
    $.ajax({
        url: "save",
        type: 'POST',
        dataType: 'json',
        data: $("#layer-form").serializeJSON(),
        success: function (res) {
            if (res.rc == 0) {
                //刷新列表
                var tableName=$('#tableName', parent.document).val();
                parent.refreshTable(tableName);
                parent.toastr.success("操作成功！");
                //关闭弹窗
                layer_close();
            } else {
                layer.msg(res.msg,{icon: 2});
            }
        }
    });
}

/**
 * 关闭弹窗
 */
function layer_close() {
    var index = parent.layer.getFrameIndex(window.name);
    //再执行关闭
    parent.layer.close(index);
}

/**
 * 初始化表格
 */
function initTable(obj) {
    if(obj.name==undefined){
        //报表
        obj.name="report";
    }

    //是否双击弹窗
    var dbClick=obj.dbClick;

    //设置表名值
    $("#tableName").val(obj.name);

    //路径配置
    var config=obj.config;
    if(config==undefined){
        config={
            index_url: '/admin/'+obj.name+'/loadData',
            add_url: '/admin/'+obj.name+'/add',
            del_url: '/admin/'+obj.name+'/del',
            table: obj.name
        };
    }

    if(obj.url!=undefined){
        config.index_url=obj.url;
    }

    //默认每页展示条数
    var pageSize=10;
    if(obj.pageSize!=undefined){
        pageSize=obj.pageSize;
    }

    var table = $('#' + config.table).find("table");
    table.bootstrapTable({
        url: config.index_url,
        pagination: true, //分页
        search: false, //显示搜索框
        sidePagination: "server", //服务端处理分页
        showToggle: true,
        showColumns: true,
        queryParams: function queryParams(params) {
            var param = $("#" + config.table +" .table-form").serializeJSON();
            param.limit=params.limit;
            param.offset=params.offset;
            param.sortOrder=params.sortOrder;
            return param;
        },
        showExport: true,
        exportDataType: "basic", //导出表格方式（默认basic：只导出当前页的表格数据；all：导出所有数据；selected：导出选中的数据）
        exportTypes: ['json', 'xml', 'csv', 'txt', 'doc', 'excel'],
        iconSize: 'outline',
        toolbar: '#' + config.table + ' .toolbar',
        clickToSelect: true,
        showRefresh: true,
        pageSize: pageSize,
        classes: "table-no-bordered",
        paginationFirstText: "首页",
        paginationPreText: '上一页',
        paginationNextText: "下一页",
        paginationLastText: "尾页",
        mobileResponsive: true,
        buttonsClass: 'default',
        iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
        icons: {
            toggle: 'glyphicon-list-alt icon-list-alt',
            columns: 'glyphicon-th icon-th',
            export: 'glyphicon-export',
            refresh: 'fa fa-refresh'
        },
        columns: obj.columns
    });

    //双击编辑
    table.on('dbl-click-row.bs.table', function (e, row, element, field) {
        if(dbClick!=false){
            layer_open(config.add_url+"?id="+row.id,"编辑");
        }
    });

    //新增
    $("#" + config.table + " .table-add").click(function () {
        layer_open(config.add_url,"新增");
    });


    //删除事件
    $("#" + config.table + " .table-del").click(function () {
        var sa = table.bootstrapTable('getSelections');
        if (sa == '' || sa == []) {
            layer.msg("请先选择数据！",{icon:2});
            return;
        }

        //批量删除 获取选中id数组
        var chk_value = [];
        for (var key in sa) {
            chk_value.push(sa[key].id);
        }
        var url = config.del_url + '?id=' + chk_value;

        table_del(url,config.table);
    });

    //普通查询显示和隐藏
    $("#" + config.table + " .table-search").click(function () {
        $("#" + config.table + " .common-search").toggle();
    });

    //查询提交
    $("#" + config.table + " .table-submit").click(function () {
        table.bootstrapTable('refresh');
    });

    //重置
    $("#" + config.table + " .table-reset").click(function () {
        $("#" + config.table +" .table-form")[0].reset();
    });
}

/**
 * 删除数据
 * @param id
 */
function table_del(url,tableName) {
    //询问框
    layer.confirm('您确定要删除吗？', {
        btn: ['确定', '取消'] //按钮
    }, function () {//确定
        //提交后台
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'json',
            success: function (res) {
                if (res.rc == 0) {
                    //刷新页面
                    layer.msg("删除成功！",{icon: 1});
                    refreshTable(tableName);
                } else {
                    layer.msg("删除失败！",{icon: 2});
                }
            }
        });
    });
}

/**
 * 单图上传方法
 * @param ctrlName
 * @param uploadUrl
 */
function initFileInput(ctrlName) {
    var uploadUrl="/admin/sys.file/uploadImage";
    var control = $('#' + ctrlName);
    var previewImg=$("#"+ctrlName+"_previewImg").val();

    var previewStr='';
    if(previewImg!=''){
        previewStr='<img src="'+previewImg+'" class="file-preview-image" style="width:auto;height:160px;">';
    }
    control.fileinput({
        language: 'zh', //设置语言
        uploadUrl: uploadUrl,  //上传地址
        showUpload: false, //是否显示上传按钮
        showRemove:true,
        dropZoneEnabled: false,
        showCaption: true,//是否显示标题
        allowedPreviewTypes: ['image'],
        allowedFileTypes: ['image'],
        allowedFileExtensions:  ['jpg', 'png'],
        maxFileSize : 2000,
        maxFileCount: 1,
        maxFilesNum: 1,
        initialPreview:previewStr//预览图片的设置
    }).on("filebatchselected", function(event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function(event, data) {
        var thumbs=data.response.path;
        //替换 "/" 为 "\"
        thumbs = thumbs.replace(/\\/g,'\/');
        $("#"+ctrlName+"_previewImg").attr("value",thumbs);
    });
}

/**
 * 刷新表格
 * @param tableName
 */
function refreshTable(tableName) {
    var table = $('#' + tableName).find("table");
    table.bootstrapTable('refresh');
}

//打开iframe弹窗
function layer_open(url,title) {
    layer.open({
        title: title,
        type: 2,
        content:url,
        shadeClose: true,
        maxmin: true,
        area: [$(window).width() > 800 ? '800px' : '95%', $(window).height() > 600 ? '600px' : '95%'],
    });
}

//基础操作
function operateBtn(name,row,btn) {
    if(btn==undefined){
        btn="edit,del";
    }
    var str="";
    //编辑
    if(btn.indexOf("edit")>=0){
        var editUrl="/admin/"+name+"/add?id=" +row.id ;
        var e = ' <button class="btn btn-primary btn-xs" type="button" onclick="layer_open(\''+editUrl+'\',\'编辑\')"><i class="fa fa-edit"></i> 编辑</button> ';
        str+=e;
    }
    //删除
    if(btn.indexOf("del")>=0){
        var delUrl="/admin/"+name+"/del?id="+row.id;
        var d = '<button class="btn btn-danger btn-xs" type="button" onclick="table_del(\''+delUrl+'\',\''+name+'\');"><i class="fa fa-trash"></i> 删除</button>';
        str+=d;
    }
    return str;
}

/**
 * 获取按钮方法
 * @param title
 * @param icon fa fa-trash
 * @param color primary,danger
 * @param dom
 * @returns {string}
 */
function getBtn(title,icon,color,dom) {
    return ' <button class="btn btn-'+color+' btn-xs" type="button" id="'+dom+'"><i class="'+icon+'"></i>&nbsp;'+title+'</button> ';
}

/**
 * 提示框
 * @param msg
 * @param dom
 */
function layer_tips(msg,dom){
    layer.tips(msg, dom, {
        tips: [2, '#3595CC'],
        time: 10000
    });
}

/**
 * 获取图片格式
 * @param value
 * @returns {string}
 */
function getImgField(value,w,h){
    if(w==undefined){
        w=50;
    }
    if(h==undefined){
        h=50;
    }
    return '<img src="'+value+ '" style="max-height:'+h+'px;max-width:'+w+'px">';
}

//模态窗口显示
function modalShow(node,body) {
    if(body!=''){
        $('#'+node+'_body').html(body);
    }
    //显示模态窗口
    $('#'+node).modal('show');
}

/**
 * 全选设置
 */
function setIcheck() {
    //初始化复选框
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });

    //全选、反选
    $('#text_box').on('ifChecked', function (event) {
        $("input[name='id']").iCheck('check');
    });
    $('#text_box').on('ifUnchecked', function (event) {
        $("input[name='id']").iCheck('uncheck');
    });
}

/**
 * 列表选中事件
 * @param id
 */
function clickIcheck(id) {
    var checked=$('#i-checks-'+id)[0].checked;
    if(checked){
        $('#i-checks-'+id).iCheck('uncheck');
    }else{
        $('#i-checks-'+id).iCheck('check');
    }
}